import config from "../config"
import { editLoadingNum, getStorage, showToast } from "../util/util"
export interface ResData<T> {
	code : number
	data : T
	message : string
}
let APIJUMPLOGIN = false
export const request = <T = any>(options : any, header ?: any, callback ?: (res ?: any) => void) => {
	return new Promise<T>((resolve, reject) => {
		let userAuth = getStorage('userAuth') || {}
		uni.request({
			url: config.apiUrl + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: header ? header : {
				authorization: userAuth.userToken ? userAuth.userToken : ''
			},
			success: (res : any) => {
				if (callback) {
					callback(res)
					return
				}
				
				if (res.data.code === 401) {
					editLoadingNum()
					// // 登录过期
					// userStore.commit('logout');
					// if (APIJUMPLOGIN === false) {
					// 	APIJUMPLOGIN = true
					// 	showToast('登录已过期', {}, () => {
					// 		uni.navigateTo({
					// 			url: '/pages/login/index'
					// 		})
					// 		setTimeout(()=>{
					// 			APIJUMPLOGIN=false
					// 		},2000)
					// 	})
					// }
					reject(res)
					return
				} else if (res.statusCode !== 200) {
					editLoadingNum()
					uni.showToast({
						'title': res.data.msg || '网络错误',
						'duration': 2000,
						'icon': 'none'
					})
					reject(res)
					return
				}
				resolve(res.data)
			},
			fail: (err) => {
				editLoadingNum()
				uni.showToast({
					'title': '请求接口失败',
					'duration': 2000,
					'icon': 'none'
				})
				reject(err)
			}
		})
	})
}